package com.leessy.r229

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.util.Log
import com.blankj.utilcode.util.NetworkUtils
import com.leessy.r229.config.Config
import com.leessy.r229.utils.PhoneUtil
import com.leessy.r229.utils.mNetUtils

/**
 * 自定义检查手机网络状态是否切换的广播接受器
 *
 * 7.0以上动态注册广播
 *
 * @author Administrator
 */
class NetBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION) {
            val netWorkState = NetUtil.getNetWorkState(context)
            Log.i("NetBroadcastReceiver", "onReceive: 网络变化广播 ：$netWorkState")
            Config.networdStatus = netWorkState

            var ip = ""
            if (Config.networdStatus == 3) ip = mNetUtils.getIpAddress("eth0")/*指定网络类型获取IP*/
            if (ip.isNullOrBlank()) {
                ip = NetworkUtils.getIPAddress(true)
            }
            Config.ipAddress = ip
        }
    }

    private object NetUtil {
        private const val NETWORK_NONE = 0 //没有连接网络
        private const val NETWORK_MOBILE = 1 //移动网络
        private const val NETWORK_WIFI = 2 //无线网络
        private const val NETWORK_ETHERNET = 3 //以太网
        fun getNetWorkState(context: Context): Int {
            // 得到连接管理器对象
            val connectivityManager = context
                .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val activeNetworkInfo = connectivityManager.activeNetworkInfo
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
                if (activeNetworkInfo.type == ConnectivityManager.TYPE_WIFI) {
                    return NETWORK_WIFI
                } else if (activeNetworkInfo.type == ConnectivityManager.TYPE_MOBILE) {
                    PhoneUtil.initIMEI()/*更新一次移动网络数据信息*/
                    return NETWORK_MOBILE
                } else if (activeNetworkInfo.type == ConnectivityManager.TYPE_ETHERNET) {
                    return NETWORK_ETHERNET
                }
            } else {
                return NETWORK_NONE
            }
            return NETWORK_NONE
        }
    }
}